<!DOCTYPE html>
<html lang="en">

<!-- Head tag (contains Google-Analytics、Baidu-Tongji)-->
<head>
  <!-- Google Analytics -->
  

  <!-- Baidu Tongji -->
  
    <script type="text/javascript">
      // Originial
      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?cdf616a127124dd7ff798963125b304d";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>
  

  <!-- Baidu Push -->
  
    <script>
      (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
          bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
          bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
      })();
    </script>
  

  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>

  <meta name="google-site-verification" content="lxDfCplOZbIzjhG34NuQBgu2gdyRlAtMB4utP5AgEBc"/>
  <meta name="baidu-site-verification" content="PpzM9WxOJU"/>

  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <meta name="description" content="It&#39;s an IT blog..."/>
  <meta name="keyword" content="zhuang,IT  blog,Blog"/>
  <link rel="shortcut icon" href="/img/avatar/java-head.png"/>

  <!-- Place this tag in your head or just before your close body tag. -->
  <script async="async" defer="defer" src="https://buttons.github.io/buttons.js"></script>

  
    <!-- Bootstrap Core CSS -->
    <link rel="stylesheet" href="/css/bootstrap.min.css"/>

    <!-- Custom CSS -->
    <link rel="stylesheet" href="/css/beantech.min.css"/>

    <!-- Pygments Highlight CSS -->
    <link rel="stylesheet" href="/css/highlight.css"/>
    <link rel="stylesheet" href="/css/widget.css"/>
    <link rel="stylesheet" href="/css/rocket.css"/>
    <link rel="stylesheet" href="/css/signature.css"/>
    <link rel="stylesheet" href="/css/catalog.css"/>
    <link rel="stylesheet" href="/css/livemylife.css"/>

    
      <!-- wave start -->
      <link rel="stylesheet" href="/css/wave.css"/>
      <!-- wave end -->
    

    
      <!-- top start (article top hot config) -->
      <link rel="stylesheet" href="/css/top.css"/>
      <!-- top end -->
    

    
      <!-- ThemeColor start -->
      <link rel="stylesheet" href="/css/scroll.css"/>
      <!-- ThemeColor end -->
    

    
      <!-- viewer start (Picture preview) -->
      <link rel="stylesheet" href="/css/viewer.min.css"/>
      <!-- viewer end -->
    

    
      <!-- Search start -->
      <link rel="stylesheet" href="/css/search.css"/>
      <!-- Search end -->
    

    
      <!-- ThemeColor start -->
      <link rel="stylesheet" href="/css/themecolor.css"/>
      <!-- ThemeColor end -->
    

    

    
  

  <!-- Custom Fonts -->
  <!-- <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
  <!-- Hux change font-awesome CDN to qiniu -->
  <link rel="stylesheet" href="https://cdn.staticfile.org/font-awesome/4.5.0/css/font-awesome.min.css" type="text/css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

  <!-- Hux Delete, sad but pending in China <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link
  href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/ css'> -->

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]-->

  <!-- ga & ba script hoook -->
  <link rel="canonical" href="http://yoursite-url/cn/java/Java NIO/">
  <title>
    
      Java NIO - either thin | or die
    
  </title>
<meta name="generator" content="Hexo 5.4.0"></head>


<!-- hack iOS CSS :active style -->

	<body ontouchstart="" class="body--light body--dark">


		<!-- ThemeColor -->
		
		<!-- ThemeColor -->
<style type="text/css">
  .body--light {
    --light-mode: none;
    --dark-mode: block;
  }
  .body--dark {
    --light-mode: block;
    --dark-mode: none;
  }
  i.mdui-icon.material-icons.light-mode {
    display: var(--light-mode);
  }
  i.mdui-icon.material-icons.dark-mode {
    display: var(--dark-mode);
  }
</style>
<div class="toggle" onclick="document.body.classList.toggle('body--dark')">
  <i class="mdui-icon material-icons light-mode"></i>
  <i class="mdui-icon material-icons dark-mode"></i>
</div>
<script>
  //getCookieValue
  function getCookieValue(a) {
    var b = document.cookie.match('(^|[^;]+)\\s*' + a + '\\s*=\\s*([^;]+)');
    return b
      ? b.pop()
      : '';
  }
  let themeMode = 'dark';
  if (getCookieValue('sb-color-mode') && (getCookieValue('sb-color-mode') !== themeMode)) {
    let dbody = document.body.classList;
    themeMode === 'dark' ? dbody.remove('body--dark') : dbody.add('body--dark');
  }

  //setCookieValue
  var toggleBtn = document.querySelector(".toggle");
  toggleBtn.addEventListener("click", function () {
    var e = document.body.classList.contains("body--dark");
    var cookieString = e
      ? "dark"
      : "light";
    var exp = new Date();
    exp.setTime(exp.getTime() + 3 * 24 * 60 * 60 * 1000); //3天过期
    document.cookie = "sb-color-mode=" + cookieString + ";expires=" + exp.toGMTString() + ";path=/";
  });
</script>

		

		<!-- Gitter -->
		

		<!-- Navigation (contains search)-->
		<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header page-scroll">
      <button type="button" class="navbar-toggle">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="/">平平淡淡</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <!-- Known Issue, found by Hux: <nav>'s height woule be hold on by its content. so, when navbar scale out, the <nav> will cover tags. also mask any touch event of tags, unfortunately. -->
    <div id="huxblog_navbar">
      <div class="navbar-collapse">
        <ul class="nav navbar-nav navbar-right">
          <li>
            <a href="/">首页</a>
          </li>

          
          
          
          
          <li>
            <a href="/archive/">
              
              归档
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/tags/">
              
              标签
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/categories/">
              
              分类
              
              
            </a>
          </li>
          
          
          
          <li>
            <a href="/about/">
              
              关于
              
              
            </a>
          </li>
          
          

          
          <li>
            <a class="popup-trigger">
              <span class="search-icon"></span>搜索</a>
          </li>
          

          <!-- LangSelect -->
          
        </ul>
      </div>
    </div>
    <!-- /.navbar-collapse -->
  </div>
  <!-- /.container -->
</nav>
<!-- progress -->
<div id="progress">
  <div class="line" style="width: 0%;"></div>
</div>

<script>
  // Drop Bootstarp low-performance Navbar Use customize navbar with high-quality material design animation in high-perf jank-free CSS3 implementation
  var $body = document.body;
  var $toggle = document.querySelector('.navbar-toggle');
  var $navbar = document.querySelector('#huxblog_navbar');
  var $collapse = document.querySelector('.navbar-collapse');

  $toggle.addEventListener('click', handleMagic)

  function handleMagic(e) {
    if ($navbar.className.indexOf('in') > 0) {
      // CLOSE
      $navbar.className = " ";
      // wait until animation end.
      setTimeout(function() {
        // prevent frequently toggle
        if ($navbar.className.indexOf('in') < 0) {
          $collapse.style.height = "0px"
        }
      }, 400)
    } else {
      // OPEN
      $collapse.style.height = "auto"
      $navbar.className += " in";
    }
  }
</script>


		<!-- Post Header (contains intro-header、signature、wordcount、busuanzi、waveoverlay) -->
		<!-- Modified by Yu-Hsuan Yen -->
<!-- Post Header -->

  <style type="text/css">
    .body--light {
      /* intro-header */
      --intro-header-background-image-url-home: url('/img/header_img/home_bg1.jpg');
      --intro-header-background-image-url-post: url('/img/header_img/lml_bg.jpg');
      --intro-header-background-image-url-page: url('//img/header_img/lml_bg.jpg');
    }
    .body--dark {
      --intro-header-background-image-url-home: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('/img/header_img/home_bg1.jpg');
      --intro-header-background-image-url-post: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('/img/header_img/lml_bg.jpg');
      --intro-header-background-image-url-page: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.2)), url('//img/header_img/lml_bg.jpg');
    }

    header.intro-header {
       /*post*/
        background-image: var(--intro-header-background-image-url-post);
        /* background-image: url('/img/header_img/lml_bg.jpg'); */
      
    }

    
      #signature {/*signature*/
        background-image: url('/img/signature/signature.png');
      }
    
  </style>





<header class="intro-header">
  <!-- Signature -->
  <div id="signature">
    <div class="container">
      <div class="row">
        <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
          
          <div class="post-heading">
            <div class="tags">
              
              <a class="tag" href="/tags/#java" title="java">java</a>
              
            </div>
            <h1>Java NIO</h1>
            <h2 class="subheading"></h2>
            <span class="meta">
              Posted by zhuang on
              2021-10-12
            </span>


            
            <!-- WordCount start -->
            <div class="blank_box"></div>
            <span class="meta">
              Estimated Reading Time <span class="post-count">21</span> Minutes
            </span>
            <div class="blank_box"></div>
            <span class="meta">
              Words <span class="post-count">4.9k</span> In Total
            </span>
            <div class="blank_box"></div>
            <!-- WordCount end -->
            
            
            <!-- 不蒜子统计 start -->
            <span class="meta" id="busuanzi_container_page_pv">
              Viewed <span id="busuanzi_value_page_pv"><i class="fa fa-spinner fa-spin"></i></span> Times
            </span>
            <!-- 不蒜子统计 end -->
            


          </div>
          
        </div>
      </div>
    </div>
  </div>

  
  <!-- waveoverlay start -->
  <div class="preview-overlay">
    <svg class="preview-waves" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 24 150 28" preserveAspectRatio="none" shape-rendering="auto">
      <defs>
        <path id="gentle-wave" d="M-160 44c30 0 58-18 88-18s 58 18 88 18 58-18 88-18 58 18 88 18 v44h-352z"></path>
      </defs>
      <g class="preview-parallax">
        <use xlink:href="#gentle-wave" x="48" y="0" fill=var(--gentle-wave1)></use>
        <use xlink:href="#gentle-wave" x="48" y="3" fill=var(--gentle-wave2)></use>
        <use xlink:href="#gentle-wave" x="48" y="5" fill=var(--gentle-wave3)></use>
        <use xlink:href="#gentle-wave" x="48" y="7" fill=var(--gentle-wave)></use>
      </g>
    </svg>
  </div>
  <!-- waveoverlay end -->
  

</header>



		<!-- Main Content (Post contains
	Pager、
	tip、
	socialshare、
	gitalk、gitment、disqus-comment、
	Catalog、
	Sidebar、
	Featured-Tags、
	Friends Blog、
	anchorjs、
	) -->
		<!-- Modify by Yu-Hsuan Yen -->
<!-- Post Content -->
<article>
  <div class="container">
    <div class="row">
      <!-- Post Container -->
      <div class="col-lg-8 col-lg-offset-1 col-md-10 col-md-offset-1 post-container">

        <p>NIO的本质就是延迟IO操作到真正发生IO的时候，而不是以前的只要IO流打开九一直等待IO操作。</p>
<p>IO：面向流、阻塞IO</p>
<p>NIO：面向缓冲区、非阻塞IO</p>
<p>Java NIO由几个核心部分组成：</p>
<ul>
<li>Channels</li>
<li>Buffers</li>
<li>Selectors</li>
</ul>
<p>Channel</p>
<p>Channel和IO的stream差不多一个等级，</p>
<p>Stream是单向的</p>
<p>Channel是双向的</p>
<p>NIO中的Channel的主要实现有：FileChannel、DatagramChannel、SocketChannel和ServerSockerChannel</p>
<p>Buffer</p>
<p>ByteBuffer、CharBuffer、IntBuffer、FloatBuffer、DoubleBuffer、LongBuffer、ShortBuffer</p>
<p>Selector</p>
<h2 id="一、Channel"><a href="#一、Channel" class="headerlink" title="一、Channel"></a>一、Channel</h2><p>Channel是一个通道，可以通过它读取和写入数据。</p>
<p>通道与流的不同之处在于通道是双向的，流只是在一个方向上移动，而通道可以用于读、写或者同时用于读写。</p>
<p>Channel用于在字节缓冲区和位于通道另一侧的实体之间有效的传输数据。</p>
<p>Java NIO的通道类似流，但又有些不同：</p>
<ul>
<li>既可以从通道中读取数据，又可以写数据到通道。但流的读写通常是单向的。</li>
<li>通道可以异步地读写</li>
<li>通道中地数据总是要先读到一个Buffer，或者总是要从一个Buffer中写入。</li>
</ul>
<h3 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h3><p>FileChannel：从文件中读写数据</p>
<p>DatagramChannel：通过UDP读写网络中的数据。</p>
<p>SockerChannel：通过TCP读写网络中的数据。</p>
<p>ServerSockerChannel：监听新进来的TCP连接，每一个新的连接都会创建一个SockerChannel。</p>
<h3 id="FileChannel"><a href="#FileChannel" class="headerlink" title="FileChannel"></a>FileChannel</h3><div class="table-container">
<table>
<thead>
<tr>
<th style="text-align:center">方法</th>
<th>描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">int read(ByteBuffer dst)</td>
<td>从Channel中读取数据到ByteBuffer</td>
</tr>
<tr>
<td style="text-align:center">long read(ByteBuffer[] dsts)</td>
<td>将Channel中的数据分散到ByteBuffer[]</td>
</tr>
<tr>
<td style="text-align:center">int write(ByteBuffer src)</td>
<td>将ByteBuffer中的数据写入到Channel</td>
</tr>
<tr>
<td style="text-align:center">long write(ByteBuffer[] srcs)</td>
<td>将ByteBuffer[] 中的数据聚集到Channel</td>
</tr>
<tr>
<td style="text-align:center">long position(long pos)</td>
<td>设置FileChannel的当前位置</td>
</tr>
<tr>
<td style="text-align:center">long size()</td>
<td>返回实例所关联文件的大小</td>
</tr>
<tr>
<td style="text-align:center">truncate()</td>
<td>截取一个文件，将指定长度后面的部分将被删除</td>
</tr>
<tr>
<td style="text-align:center">force()</td>
<td>将尚未写入磁盘的数据强制写到磁盘上。</td>
</tr>
<tr>
<td style="text-align:center">transferTo()和transferFrom()</td>
<td>通道之间的数据传输</td>
</tr>
</tbody>
</table>
</div>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">FileChannelDemo</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * FileChannel 读操作</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">readOperation</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 打开FileChannel</span></span><br><span class="line">        RandomAccessFile accessFile = <span class="keyword">new</span> RandomAccessFile(<span class="string">&quot;F:\\备忘录.txt&quot;</span>, <span class="string">&quot;rw&quot;</span>);</span><br><span class="line">        FileChannel channel = accessFile.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建Buffer</span></span><br><span class="line">        ByteBuffer buffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 读取数据</span></span><br><span class="line">        <span class="keyword">while</span> (channel.read(buffer) != -<span class="number">1</span>) &#123;</span><br><span class="line">            buffer.flip();</span><br><span class="line">            <span class="keyword">while</span> (buffer.hasRemaining()) &#123;</span><br><span class="line">                System.out.print((<span class="keyword">char</span>) buffer.get());</span><br><span class="line">            &#125;</span><br><span class="line">            buffer.clear();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 关闭</span></span><br><span class="line">        channel.close();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * FileChannel 写操作</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">writeOperation</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// 打开FileChannel</span></span><br><span class="line">        RandomAccessFile accessFile = <span class="keyword">new</span> RandomAccessFile(<span class="string">&quot;F:\\test.txt&quot;</span>, <span class="string">&quot;rw&quot;</span>);</span><br><span class="line">        FileChannel channel = accessFile.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建Buffer</span></span><br><span class="line">        ByteBuffer buffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">        buffer.clear();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 写入内容</span></span><br><span class="line">        String data = <span class="string">&quot;FileChannel&quot;</span>;</span><br><span class="line">        buffer.put(data.getBytes());</span><br><span class="line">        buffer.flip();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (buffer.hasRemaining()) &#123;</span><br><span class="line">            channel.write(buffer);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        channel.close();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * transferFrom transferTo操作</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">transferFromOperation</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">        <span class="comment">// 打开FileChannel</span></span><br><span class="line">        RandomAccessFile accessFile1 = <span class="keyword">new</span> RandomAccessFile(<span class="string">&quot;F:\\test1.txt&quot;</span>, <span class="string">&quot;rw&quot;</span>);</span><br><span class="line">        FileChannel channel1 = accessFile1.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 打开FileChannel</span></span><br><span class="line">        RandomAccessFile accessFile2 = <span class="keyword">new</span> RandomAccessFile(<span class="string">&quot;F:\\test2.txt&quot;</span>, <span class="string">&quot;rw&quot;</span>);</span><br><span class="line">        FileChannel channel2 = accessFile2.getChannel();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">long</span> position = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">long</span> size = channel1.size();</span><br><span class="line">        <span class="comment">// channel2.transferFrom(channel1, position, size);</span></span><br><span class="line">        channel1.transferTo( position, size, channel2);</span><br><span class="line"></span><br><span class="line">        channel1.close();</span><br><span class="line">        channel2.close();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Socket通道"><a href="#Socket通道" class="headerlink" title="Socket通道"></a>Socket通道</h3><p>DatagramChannel和SocketChannel实现定义读和写功能的接口而ServerSocketChannel不实现。ServerSocketChannel负责监听传入的连接和传教新的SocketChannel对象，从不传输数据。</p>
<h4 id="ServerSocketChannel"><a href="#ServerSocketChannel" class="headerlink" title="ServerSocketChannel"></a>ServerSocketChannel</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">test</span><span class="params">()</span> <span class="keyword">throws</span> IOException, InterruptedException </span>&#123;</span><br><span class="line">        <span class="comment">// 端口号</span></span><br><span class="line">        <span class="keyword">int</span> port = <span class="number">8888</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 缓冲区</span></span><br><span class="line">        ByteBuffer buffer = ByteBuffer.wrap(<span class="string">&quot;helloworld&quot;</span>.getBytes());</span><br><span class="line"></span><br><span class="line">        <span class="comment">// ServerSocketChannel</span></span><br><span class="line">        ServerSocketChannel serverSocket = ServerSocketChannel.open();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 绑定</span></span><br><span class="line">        serverSocket.socket().bind(<span class="keyword">new</span> InetSocketAddress(port));</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 设置非阻塞模式</span></span><br><span class="line">        serverSocket.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            SocketChannel socket = serverSocket.accept();</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">null</span> == socket) &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;等待连接中...&quot;</span>);</span><br><span class="line">                Thread.sleep(<span class="number">2000</span>);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                System.out.println(socket.socket().getRemoteSocketAddress());</span><br><span class="line">                buffer.rewind();</span><br><span class="line">                socket.write(buffer);</span><br><span class="line">                socket.close();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h3 id="SocketChannel"><a href="#SocketChannel" class="headerlink" title="SocketChannel"></a>SocketChannel</h3><p>  是一个连接到TCP网络套接字的通道。</p>
<ul>
<li>用来连接Socket套接字</li>
<li>用来处理网络I/O的通道</li>
<li>基于TCP连接传输</li>
<li>实现可选择通道，可以被多路复用</li>
</ul>
<h3 id="DatagramChannel"><a href="#DatagramChannel" class="headerlink" title="DatagramChannel"></a>DatagramChannel</h3><h3 id="FileChannel-1"><a href="#FileChannel-1" class="headerlink" title="FileChannel"></a>FileChannel</h3><h2 id="二、Buffer"><a href="#二、Buffer" class="headerlink" title="二、Buffer"></a>二、Buffer</h2><p>Java NIO中的Buffer用于和NIO通道进行交互，数据从通道读入缓冲区，从缓冲区写入到通道中的。</p>
<p><img src="image-20211013144757332.png" alt="image-20211013144757332"></p>
<p>所有的缓冲区类型都继承与抽象类Buffer，常用ByteBuffer</p>
<h3 id="1、基本用法"><a href="#1、基本用法" class="headerlink" title="1、基本用法"></a>1、基本用法</h3><p>（1）写入数据到Buffer</p>
<p>（2）调用flip()方法进行模式转换</p>
<p>（3）从Buffer中读取数据</p>
<p>（4）调用clear()方法或者compact()方法</p>
<h3 id="2、capacity、position、limit"><a href="#2、capacity、position、limit" class="headerlink" title="2、capacity、position、limit"></a>2、capacity、position、limit</h3><p>position和limit的含义取决于Buffer处于读模式还是写模式。</p>
<p><img src="image-20211013162752771.png" alt="image-20211013162752771"></p>
<p>（1）capacity：固定的大小值</p>
<p>（2）position</p>
<p>写数据时，position表示写入数据的当前位置，初始值为0，最大capacity - 1；</p>
<p>读数据时，position表示读入数据的当前位置</p>
<p>（3）limit</p>
<p>写数据，limit表示最多写入多少个数据，等于capacity</p>
<p>读数据，limit表示有多少可读数据（not null的数据），能读到之前写入的所有数据（limit设置成以写数据的数量，这个值在写模式下就是position）</p>
<h3 id="3、Buffer-分配和写数据、读数据"><a href="#3、Buffer-分配和写数据、读数据" class="headerlink" title="3、Buffer 分配和写数据、读数据"></a>3、Buffer 分配和写数据、读数据</h3><p>（1）分配</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ByteBuffer buf = ByteBuffer.allocate(<span class="number">1024</span>);</span><br></pre></td></tr></table></figure>
<p>(2) 写数据</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 两种方法</span></span><br><span class="line"><span class="comment">// 1、从Channel写到Buffer</span></span><br><span class="line"><span class="keyword">int</span> bytesRead = channel.read(buf);</span><br><span class="line"><span class="comment">// 2、通过Buffer的put()方法写到Buffer中</span></span><br><span class="line">buf.put(<span class="number">100</span>);</span><br></pre></td></tr></table></figure>
<p>(3) filp()方法</p>
<p>将Buffer从写模式切换到读模式，position设置0，limit设置之前的position的值</p>
<p>（4）读数据</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 两种方法</span></span><br><span class="line"><span class="comment">// 1、从Buffer读取数据到Channel种</span></span><br><span class="line"><span class="keyword">int</span> byteWrite = channel.write(buf);</span><br><span class="line"><span class="comment">// 2、使用get()方法读取数据</span></span><br><span class="line"><span class="keyword">byte</span> <span class="keyword">byte</span> = buf.get();</span><br></pre></td></tr></table></figure>
<h3 id="4、方法"><a href="#4、方法" class="headerlink" title="4、方法"></a>4、方法</h3><h4 id="rewind-方法"><a href="#rewind-方法" class="headerlink" title="rewind()方法"></a>rewind()方法</h4><p>将position设置0</p>
<h4 id="clear-与compact-方法"><a href="#clear-与compact-方法" class="headerlink" title="clear()与compact()方法"></a>clear()与compact()方法</h4><p>调用clear()方法，position设置为0，limit设置为capacity的值，Buffer清空，但数据并未清除，只是标记从哪里开始写数据</p>
<p>调用compact()方法，将维度的数据拷贝到Buffer起始处，然后将position设置到最后一个未读元素正后面，limit依然设置为capacity，写数据不会覆盖未读的数据。</p>
<h4 id="mark-与reset-方法"><a href="#mark-与reset-方法" class="headerlink" title="mark()与reset()方法"></a>mark()与reset()方法</h4><p>Buffer.mark()可标记Buffer中的一个特定position，之后可通过Buufer.reset()方法恢复到这个position</p>
<h3 id="5、缓冲区操作"><a href="#5、缓冲区操作" class="headerlink" title="5、缓冲区操作"></a>5、缓冲区操作</h3><h4 id="5-1-缓冲区分片"><a href="#5-1-缓冲区分片" class="headerlink" title="5.1 缓冲区分片"></a>5.1 缓冲区分片</h4><p>根据现有的缓冲区对象来创建一个子缓冲区，调用<code>slice()</code>创建一个子缓冲区。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建缓冲区</span></span><br><span class="line">        ByteBuffer buffer = ByteBuffer.allocate(<span class="number">10</span>);</span><br><span class="line">        <span class="comment">// 向缓冲区写入数据</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; buffer.capacity(); i++) &#123;</span><br><span class="line">            buffer.put((<span class="keyword">byte</span>) i);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 创建子缓冲区</span></span><br><span class="line">        buffer.position(<span class="number">3</span>);</span><br><span class="line">        buffer.limit(<span class="number">7</span>);</span><br><span class="line">        ByteBuffer slice = buffer.slice();</span><br><span class="line">        <span class="comment">// 改变子缓冲区的内容</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; slice.capacity(); i++) &#123;</span><br><span class="line">            <span class="keyword">byte</span> b = slice.get(i);</span><br><span class="line">            b *= <span class="number">10</span>;</span><br><span class="line">            slice.put(i, b);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 将位置重置</span></span><br><span class="line">        buffer.position(<span class="number">0</span>);</span><br><span class="line">        buffer.limit(buffer.capacity());</span><br><span class="line">        <span class="comment">// 输出缓冲区内容</span></span><br><span class="line">        <span class="keyword">while</span> (buffer.remaining() &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            System.out.println(buffer.get());</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>
<h4 id="5-2-只读缓冲区"><a href="#5-2-只读缓冲区" class="headerlink" title="5.2 只读缓冲区"></a>5.2 只读缓冲区</h4><p>可读取，不能向其写入数据，调用<code>asReadOnlyBuffer()</code>方法,将任何常规缓冲区转为只读缓冲区，与原缓冲区共享数据，不过时只读。修改只读缓冲区，会报ReadOnlyBufferException异常。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建缓冲区</span></span><br><span class="line">        ByteBuffer buffer = ByteBuffer.allocate(<span class="number">10</span>);</span><br><span class="line">        <span class="comment">// 向缓冲区写入数据</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; buffer.capacity(); i++) &#123;</span><br><span class="line">            buffer.put((<span class="keyword">byte</span>) i);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 创建只读缓冲区</span></span><br><span class="line">        ByteBuffer readOnly = buffer.asReadOnlyBuffer();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 修改原缓冲区的内容</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; buffer.capacity(); i++) &#123;</span><br><span class="line">            <span class="keyword">byte</span> b = buffer.get(i);</span><br><span class="line">            b *= <span class="number">10</span>;</span><br><span class="line">            buffer.put(i, b);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        readOnly.position(<span class="number">0</span>);</span><br><span class="line">        readOnly.limit(readOnly.capacity());</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (readOnly.remaining() &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            System.out.print(readOnly.get() + <span class="string">&quot; &quot;</span>);</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>
<h4 id="5-3-直接缓冲区"><a href="#5-3-直接缓冲区" class="headerlink" title="5.3 直接缓冲区"></a>5.3 直接缓冲区</h4><p>加快IO速度，使用一种特殊方式为其分配内存的缓冲区，分配直接缓冲区，调用<code>allocateDirect()</code>方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"> </span><br><span class="line">FileInputStream inputStream = <span class="keyword">new</span> FileInputStream(<span class="string">&quot;resources\\test1.txt&quot;</span>);</span><br><span class="line">FileChannel inputChannel = inputStream.getChannel();</span><br><span class="line"></span><br><span class="line">FileOutputStream outputStream = <span class="keyword">new</span> FileOutputStream(<span class="string">&quot;resources\\test2.txt&quot;</span>);</span><br><span class="line">FileChannel outputChannel = outputStream.getChannel();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 创建直接缓冲区</span></span><br><span class="line">ByteBuffer buffer = ByteBuffer.allocateDirect(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">    buffer.clear();</span><br><span class="line">    <span class="keyword">if</span> (inputChannel.read(buffer) == -<span class="number">1</span>)&#123;<span class="keyword">break</span>;&#125;</span><br><span class="line">    buffer.flip();</span><br><span class="line">    outputChannel.write(buffer);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="5-4-内存映射文件I-O"><a href="#5-4-内存映射文件I-O" class="headerlink" title="5.4 内存映射文件I/O"></a>5.4 内存映射文件I/O</h4><p>内存映射文件是一种读和写文件数据的方法，比常规的基于流或者基于通道IO快的多，是通过使文件中的数据出现为内存数组的内容来完成的，只有文件中实际读取或者写入的部分才会映射到内存中</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> <span class="keyword">int</span> start = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">int</span> size = <span class="number">1024</span>;</span><br><span class="line">        RandomAccessFile randomAccessFile = <span class="keyword">new</span> RandomAccessFile(<span class="string">&quot;resources\\test1.txt&quot;</span>, <span class="string">&quot;rw&quot;</span>);</span><br><span class="line">            FileChannel channel = randomAccessFile.getChannel();</span><br><span class="line"></span><br><span class="line">            MappedByteBuffer byteBuffer = channel.map(</span><br><span class="line">                    FileChannel.MapMode.READ_WRITE,</span><br><span class="line">                    start, size );</span><br><span class="line"></span><br><span class="line">            byteBuffer.put(<span class="number">0</span>, (<span class="keyword">byte</span>) <span class="number">97</span>);</span><br><span class="line">            byteBuffer.put(<span class="number">1023</span>, (<span class="keyword">byte</span>) <span class="number">122</span>);</span><br></pre></td></tr></table></figure>
<h2 id="三、Selector"><a href="#三、Selector" class="headerlink" title="三、Selector"></a>三、Selector</h2><p>selector称为选择器、多路复用，用于检查一个或多个NIO Channel的状态是否处于可读、可写。</p>
<p><img src="image-20211013170807972.png" alt="image-20211013170807972"></p>
<p>使用更少的线程来处理通道，避免了线程上下文切换带来的开销</p>
<p>（1）不是所有的Channel都可被Selector复用。FileChannel不能被复用，判断使是否继承一个抽象类SelectableChannel，继承则可复用。</p>
<p>（2）SelectableChannel提供了实现通道的可选择性所需要的公共方法，是所有支持就绪检查的通道类的父类。</p>
<p>（3）一个通道可以被注册到多个选择器，但对每个选择器而言只能被注册一次。SelectableChannel可以注册到Selector对象上，在注册时，需要指定通道的哪些操作，是Selector感兴趣的</p>
<p><img src="image-20211013171634884.png" alt="image-20211013171634884"></p>
<h3 id="Channel注册到Selector"><a href="#Channel注册到Selector" class="headerlink" title="Channel注册到Selector"></a>Channel注册到Selector</h3><p>使用Channel.register(Selector sel, int ops)方法，将一个通道注册到一个选择中。</p>
<ul>
<li>sel：指定通道要注册的选择器</li>
<li>ops：指定选择器需要查询的通道操作<ul>
<li>可读：SelectionKey.OP_READ</li>
<li>可写：SelectionKey.OP_WRITE</li>
<li>连接：SelectionKey.OP_CONNECT</li>
<li>接受：SelectionKey.OP_ACCEPT</li>
</ul>
</li>
</ul>
<p>对通道的多操作类感兴趣，可用“位或”操作符来实现</p>
<p>int key = SelectionKey.OP_READ | SelectionKey.OP_WRITE;</p>
<p>选择器查询的不是通道的操作，而是通道的某个操作的一种就绪状态。一旦通道具备完成某个操作的条件，表示该通道的某个操作已经就绪，可被Selector擦好像到。</p>
<h3 id="选择键（SelectionKey）"><a href="#选择键（SelectionKey）" class="headerlink" title="选择键（SelectionKey）"></a>选择键（SelectionKey）</h3><p>（1）使用选择器Selector的select()方法，对感兴趣的通道操作，进行就绪状态的查询。</p>
<p>（2）Selector不断查询Channel中发生的操作的就绪状态，一旦通道有操作的就绪状态达成，并且时selector感兴趣的操作，就会被Selector选中，放入选择键集合中。</p>
<p>（3）一个选择键，包含了注册再Selector的通道操作的类型、特定的通道与特定的选择器之间的注册关系。</p>
<p>（4）选择器和事件的概念比较相似，一个选择键类似监听器模式里面的一个事件，Selector不是事件触发的，而是主动去查询的模式。</p>
<h3 id="使用方法"><a href="#使用方法" class="headerlink" title="使用方法"></a>使用方法</h3><ul>
<li>与Selector一起使用，Channel必须处于非阻塞模式下，FileChannel不能与Selector一起使用，FileChannel不能切换到非阻塞模式。</li>
</ul>
<p>NIO编程步骤：</p>
<p>第一步：创建ServerSocketChannel通道，绑定监听端口</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取通道</span></span><br><span class="line">        ServerSocketChannel serverSocket = ServerSocketChannel.open();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 绑定端口号</span></span><br><span class="line">        serverSocket.bind(<span class="keyword">new</span> InetSocketAddress(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">8888</span>));</span><br></pre></td></tr></table></figure>
<p>第二步：设置通道为非阻塞模式</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 设置非阻塞</span></span><br><span class="line">        serverSocket.configureBlocking(<span class="keyword">false</span>);</span><br></pre></td></tr></table></figure>
<p>第三步：创建Selector选择器</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取Selector选择器</span></span><br><span class="line">        Selector selector = Selector.open();</span><br></pre></td></tr></table></figure>
<p>第四步：将Channel注册到Selector选择器上，监听连接事件</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 注册到selector选择器上，监听接收事件</span></span><br><span class="line">        serverSocket.register(selector, SelectionKey.OP_ACCEPT);</span><br></pre></td></tr></table></figure>
<p>第五步：调用Selector的select方法，轮询查询</p>
<p>Selector的select()方法，可以查询出已经就绪的通道操作，这些就绪状态集合，保存在一个元素市SelectionKey对象的Set集合中。</p>
<ul>
<li>select()：阻塞至少有一个通道在你注册的事件上就绪了；</li>
<li>select(long timeout)：和select()一样，但最长阻塞事件未timeout毫秒</li>
<li>selectNow()：非阻塞，只要有通道就绪就立刻返回。</li>
</ul>
<p>select()返回的int值，表示有多少通道已经就绪，自前一次select方法以来到这一次select方法之间的时间段上，有多少通道变就绪状态。返回值不为0时，在Selector中有一个selectedKeys()方法，用来访问已选择键集合，迭代集合的每一个选择键元素，根据就绪操作的类型，完成对应的操作。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> select = selector.select();</span><br></pre></td></tr></table></figure>
<p>第六步：调用selectKeys方法获取就绪Channel集合</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Set&lt;SelectionKey&gt; selectionKeys = selector.selectedKeys();</span><br></pre></td></tr></table></figure>
<p>第七步：遍历就绪 Channel集合，判断就绪事件类型，实现具体的业务的操作</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">Iterator&lt;SelectionKey&gt; iterator = selectionKeys.iterator();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (iterator.hasNext()) &#123;</span><br><span class="line">            SelectionKey key = iterator.next();</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (key.isAcceptable()) &#123;</span><br><span class="line"></span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (key.isConnectable()) &#123;</span><br><span class="line"></span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (key.isReadable()) &#123;</span><br><span class="line"></span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (key.isWritable()) &#123;</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            iterator.remove();</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>
<p>第八步：根据业务，是否需要再次注册 监听事件，重复执行</p>
<p>第九步：停止选择</p>
<p>选择器执行选择的过程，系统底层依次询问每个通道是否已经就绪，这过程会造成调用线程进行阻塞状态，有以下三种方式可以唤醒select()方法中阻塞的线程：</p>
<ul>
<li>wakeup()方法：通过调用Selector对象的wakeup()方法让处于阻塞状态的select()方法立刻返回。方法使得选择器上的第一个还没有返回的选择操作立即返回，如果当前没有进行中的选择操作，那么下一次对select()方法的一次调用将立即返回。</li>
<li>close()：通过close()方法关闭Selector，使得任何一个在选择操作中阻塞的线程都被唤醒，同时使得注册到该Selector的所有Channel被注销，所有的键将被取消，但是Channel本身并不会关闭。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">serverTest</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();</span><br><span class="line">        serverSocketChannel.socket().bind(<span class="keyword">new</span> InetSocketAddress( <span class="number">8888</span>));</span><br><span class="line">        serverSocketChannel.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line"></span><br><span class="line">        Selector selector = Selector.open();</span><br><span class="line">        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);</span><br><span class="line"></span><br><span class="line">        ByteBuffer readBuffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">        ByteBuffer writerBuffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">        writerBuffer.put(<span class="string">&quot;received&quot;</span>.getBytes());</span><br><span class="line">        writerBuffer.flip();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            <span class="keyword">int</span> select = selector.select();</span><br><span class="line">            Set&lt;SelectionKey&gt; selectionKeys = selector.selectedKeys();</span><br><span class="line">            Iterator&lt;SelectionKey&gt; iterator = selectionKeys.iterator();</span><br><span class="line">            <span class="keyword">while</span> (iterator.hasNext()) &#123;</span><br><span class="line">                SelectionKey key = iterator.next();</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span> (key.isAcceptable()) &#123;</span><br><span class="line">                    SocketChannel accept = serverSocketChannel.accept();</span><br><span class="line">                    accept.configureBlocking(<span class="keyword">false</span>);</span><br><span class="line">                    accept.register(selector, SelectionKey.OP_READ);</span><br><span class="line">                &#125; <span class="keyword">else</span> <span class="keyword">if</span> (key.isWritable()) &#123;</span><br><span class="line">                    writerBuffer.rewind();</span><br><span class="line">                    SocketChannel socketChannel = (SocketChannel) key.channel();</span><br><span class="line">                    socketChannel.write(writerBuffer);</span><br><span class="line">                    key.interestOps(SelectionKey.OP_READ);</span><br><span class="line">                &#125; <span class="keyword">else</span> <span class="keyword">if</span> (key.isReadable()) &#123;</span><br><span class="line">                    SocketChannel socketChannel = (SocketChannel) key.channel();</span><br><span class="line">                    readBuffer.clear();</span><br><span class="line">                    socketChannel.read(readBuffer);</span><br><span class="line"></span><br><span class="line">                    readBuffer.flip();</span><br><span class="line">                    System.out.println(<span class="string">&quot;received:&quot;</span> + <span class="keyword">new</span> String(readBuffer.array()));</span><br><span class="line">                    key.interestOps(SelectionKey.OP_WRITE);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                iterator.remove();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Test</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">clientTest</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        SocketChannel socketChannel = SocketChannel.open(</span><br><span class="line">                <span class="keyword">new</span> InetSocketAddress(<span class="string">&quot;127.0.0.1&quot;</span>, <span class="number">8888</span>));</span><br><span class="line"></span><br><span class="line">        ByteBuffer writerBuffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">        ByteBuffer readBuffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line">        writerBuffer.put(<span class="string">&quot;hello&quot;</span>.getBytes());</span><br><span class="line">        writerBuffer.flip();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">            writerBuffer.rewind();</span><br><span class="line">            socketChannel.write(writerBuffer);</span><br><span class="line">            readBuffer.clear();</span><br><span class="line">            socketChannel.read(readBuffer);</span><br><span class="line">            System.out.println(<span class="keyword">new</span> String(readBuffer.array()));</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h2 id="四、Pipe"><a href="#四、Pipe" class="headerlink" title="四、Pipe"></a>四、Pipe</h2><p>管道时2个线程之间的单向数据连接，Pipe有一个source通道和一个sink通道，数据会被写到sink通道，从source通道读取。</p>
<p><img src="image-20211014190335299.png" alt="image-20211014190335299"></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建管道</span></span><br><span class="line">        Pipe pipe = Pipe.open();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 写入管道</span></span><br><span class="line">        ByteBuffer writerBuffer = ByteBuffer.allocate(<span class="number">10</span>);</span><br><span class="line">        writerBuffer.put(<span class="string">&quot;HelloWorld&quot;</span>.getBytes());</span><br><span class="line">        writerBuffer.flip();</span><br><span class="line"></span><br><span class="line">        Pipe.SinkChannel sink = pipe.sink();</span><br><span class="line">        <span class="keyword">while</span> (writerBuffer.hasRemaining()) &#123;</span><br><span class="line">            sink.write(writerBuffer);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 读取数据</span></span><br><span class="line">        ByteBuffer readBuffer = ByteBuffer.allocate(<span class="number">10</span>);</span><br><span class="line">        readBuffer.clear();</span><br><span class="line"></span><br><span class="line">        Pipe.SourceChannel source = pipe.source();</span><br><span class="line">        <span class="keyword">int</span> length = source.read(readBuffer);</span><br><span class="line">        System.out.println(<span class="keyword">new</span> String(readBuffer.array(), <span class="number">0</span>, length));</span><br><span class="line"></span><br><span class="line">        source.close();</span><br><span class="line">        sink.close();</span><br></pre></td></tr></table></figure>
<h2 id="五、FileLock"><a href="#五、FileLock" class="headerlink" title="五、FileLock"></a>五、FileLock</h2><p>文件锁时进程级别的，不是线程级别的。文件锁可以解决多个进程并发访问、修改同一文件的问题。使用文件锁时，同一进程内的多个线程，可以同时访问、修改次文件。</p>
<p>文件锁是当前程序所属的JVM实例持有的，一旦获取文件锁，要调用release()、关闭对应的FileChannel对象，或者当前JVM退出，才释放锁。</p>
<p>文件锁分类：排他锁、共享锁</p>
<p>文件锁要通过FileChannel对象使用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">FileChannel fileChannel = <span class="keyword">new</span> FileOutputStream(<span class="string">&quot;&quot;</span>).getChannel();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 对文件加锁</span></span><br><span class="line">FileLock lock = fileChannel.lock();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 释放锁</span></span><br><span class="line">lock.release();</span><br></pre></td></tr></table></figure>
<p>获取锁的4种方法</p>
<ul>
<li>lock() ：对整个文件加锁，默认为排他锁</li>
<li>lock(long position, long size, boolean shared)：自定义加锁方法，position、size指定要加锁的部分，shared指定是否共享锁。</li>
<li>tryLock()：对整个文件加锁，默认排他锁</li>
<li>tryLock(long position, long size, boolean shared)</li>
</ul>
<p>lock与tryLock的区别：</p>
<ul>
<li>lock是阻塞式的，如果未获取到文件锁，会一直阻塞当前线程，直到获取文件锁；</li>
<li>tryLock是非阻塞的，tryLock是尝试获取文件锁，获取成功九返回锁对象，否则返回null，不会阻塞当前线程</li>
</ul>
<p>两个方法：</p>
<ul>
<li>boolean isShared(): 文件是否未共享锁</li>
<li>boolean isValid(): 文件是否还有效</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">ByteBuffer buffer = ByteBuffer.wrap(<span class="string">&quot;nihao&quot;</span>.getBytes());</span><br><span class="line"></span><br><span class="line">        Path path = Paths.get(<span class="string">&quot;resources\\test1.txt&quot;</span>);</span><br><span class="line"></span><br><span class="line">        FileChannel channel = FileChannel.open(</span><br><span class="line">                path, StandardOpenOption.WRITE, StandardOpenOption.APPEND</span><br><span class="line">        );</span><br><span class="line">        channel.position(channel.size() - <span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">        FileLock fileLock = channel.tryLock(<span class="number">0</span>, Long.MAX_VALUE, <span class="keyword">false</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;共享锁: &quot;</span> + fileLock.isShared());</span><br><span class="line"></span><br><span class="line">        channel.write(buffer);</span><br><span class="line">        channel.close();</span><br><span class="line">        System.out.println(<span class="string">&quot;写操作完成&quot;</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        BufferedReader bufferedReader = <span class="keyword">new</span> BufferedReader(<span class="keyword">new</span> FileReader(<span class="string">&quot;resources\\test1.txt&quot;</span>));</span><br><span class="line">        String line = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">while</span> ((line = bufferedReader.readLine()) != <span class="keyword">null</span>) &#123;</span><br><span class="line">            System.out.println(line);</span><br><span class="line">        &#125;</span><br><span class="line">        bufferedReader.close();</span><br></pre></td></tr></table></figure>
<h2 id="六、Path与Files"><a href="#六、Path与Files" class="headerlink" title="六、Path与Files"></a>六、Path与Files</h2><h3 id="Path"><a href="#Path" class="headerlink" title="Path"></a>Path</h3><p>Path接口是在Java7中添加到Java NIO。Path接口位于java.nio.file包中。</p>
<p>Path实例表示文件系统中的路径，一个路径可以指向一个文件或一个目录</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建绝对路径</span></span><br><span class="line">        Path path = Paths.get(<span class="string">&quot;d:\\resources\\test1.txt&quot;</span>);</span><br><span class="line">        System.out.println(path);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建相对路径  d:\resources\projects 目录</span></span><br><span class="line">        Path path1 = Paths.get(<span class="string">&quot;d:\\resources&quot;</span>, <span class="string">&quot;projects&quot;</span>);</span><br><span class="line">        System.out.println(path1);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// d:\resources\projects\test1.txt 文件</span></span><br><span class="line">        Path path2 = Paths.get(<span class="string">&quot;d:\\resources&quot;</span>, <span class="string">&quot;projects\\test1.txt&quot;</span>);</span><br><span class="line">        System.out.println(path2);</span><br><span class="line"></span><br><span class="line">        String pathStr = <span class="string">&quot;d:\\resources\\projects\\..\\yyds&quot;</span>;</span><br><span class="line">        Path path3 = Paths.get(pathStr);</span><br><span class="line">        System.out.println(path3);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// normalize()方法可以使路径标准化，意味着将一出所有在路径字符串的中间的.和..代码</span></span><br><span class="line">        Path normalize = path3.normalize();</span><br><span class="line">        System.out.println(normalize);</span><br></pre></td></tr></table></figure>
<h3 id="Files"><a href="#Files" class="headerlink" title="Files"></a>Files</h3><ol>
<li><p>Files.createDirectory()：根据Path实例创建一个新目录</p>
</li>
<li><p>Files.copy()</p>
</li>
</ol>
<p>从一个路径拷贝一个文件到另外一个目录</p>
<p>覆盖已存在的文件，第三个参数，如果目标已存在，将覆盖现有文件</p>
<ol>
<li><p>Files.move()：将文件从一个路径移动到另一个路径</p>
</li>
<li><p>Files.delete()：删除一个文件或目录</p>
</li>
<li>Files.walkFileTree()：</li>
</ol>
<p>（1）包含递归遍历目录树功能，Path实例指向要遍历的目录、FileVisitor在遍历期间被调用</p>
<p>（2）FileVisitor是一个接口，必须实现接口，如不需要，可以扩展SimpleFileVisitor类，包含FileVisitor接口中所有方法的默认实现。</p>
<p>（3）FileVisitor接口中的方法，都返回一个FileVisitResult枚举实例</p>
<ul>
<li>CONTINUE： 继续</li>
<li>TERMINATE 终止</li>
<li>SKIP_SIBLING 跳过同级</li>
<li>SKIP_SUBTREE 跳过子级</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">Files.walkFileTree(Paths.get(<span class="string">&quot;resources&quot;</span>),</span><br><span class="line">                    <span class="keyword">new</span> SimpleFileVisitor&lt;Path&gt;() &#123;</span><br><span class="line">                        <span class="meta">@Override</span></span><br><span class="line">                        <span class="function"><span class="keyword">public</span> FileVisitResult <span class="title">visitFile</span><span class="params">(Path file, BasicFileAttributes attrs)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">                            String string = file.toAbsolutePath().toString();</span><br><span class="line">                            <span class="keyword">if</span> (string.endsWith(<span class="string">&quot;test1.txt&quot;</span>)) &#123;</span><br><span class="line">                                System.out.println(<span class="string">&quot;file found at path:&quot;</span> + file.toAbsolutePath());</span><br><span class="line">                                <span class="keyword">return</span> FileVisitResult.TERMINATE;</span><br><span class="line">                            &#125;</span><br><span class="line">                            <span class="keyword">return</span> FileVisitResult.CONTINUE;</span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;);</span><br></pre></td></tr></table></figure>
<h2 id="七、AsynchronousFileChannel"><a href="#七、AsynchronousFileChannel" class="headerlink" title="七、AsynchronousFileChannel"></a>七、AsynchronousFileChannel</h2><p>在Java 7，添加<code>AsynchronousFileChannel</code>,异步的将数据写入文件。</p>
<p>1、创建AsychronousFileChannel，通过open(Path file, OpenOption options)创建</p>
<ul>
<li>file：相关联文件的path实例</li>
<li>options：执行什么操作</li>
</ul>
<p>2、读取数据两种方法</p>
<p>第一种方法是调用返回Future的read()方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">AsynchronousFileChannel fileChannel = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            fileChannel =</span><br><span class="line">                    AsynchronousFileChannel.open(Paths.get(<span class="string">&quot;resources\\test1.txt&quot;</span>), StandardOpenOption.READ);</span><br><span class="line"></span><br><span class="line">            ByteBuffer buffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line">            Future&lt;Integer&gt; read = fileChannel.read(buffer, <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">while</span> (!read.isDone());</span><br><span class="line"></span><br><span class="line">            buffer.flip();</span><br><span class="line"></span><br><span class="line">            System.out.println(<span class="keyword">new</span> String(buffer.array()));</span><br><span class="line">            buffer.clear();</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">null</span> != fileChannel) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    fileChannel.close();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>
<p>第二种方法CompletionHandler读取数据</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">fileChannel =</span><br><span class="line">                    AsynchronousFileChannel.open(Paths.get(<span class="string">&quot;resources\\test1.txt&quot;</span>), StandardOpenOption.READ);</span><br><span class="line"></span><br><span class="line">            ByteBuffer buffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line"></span><br><span class="line">            fileChannel.read(buffer, <span class="number">0</span>, buffer, <span class="keyword">new</span> CompletionHandler&lt;Integer, ByteBuffer&gt;() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">completed</span><span class="params">(Integer result, ByteBuffer attachment)</span> </span>&#123;</span><br><span class="line">                    attachment.flip();</span><br><span class="line"></span><br><span class="line">                    System.out.println(<span class="keyword">new</span> String(attachment.array()));</span><br><span class="line">                    attachment.clear();</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">failed</span><span class="params">(Throwable exc, ByteBuffer attachment)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br></pre></td></tr></table></figure>
<p>3、写入数据两种方法</p>
<p>文件必须存在，不存在抛出异常</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">fileChannel =</span><br><span class="line">                    AsynchronousFileChannel.open(Paths.get(<span class="string">&quot;resources\\test3.txt&quot;</span>), StandardOpenOption.WRITE);</span><br><span class="line"></span><br><span class="line">            ByteBuffer buffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">            buffer.put(<span class="string">&quot;asynchronousFileChannel&quot;</span>.getBytes());</span><br><span class="line">            buffer.flip();</span><br><span class="line">            Future&lt;Integer&gt; writeOperation = fileChannel.write(buffer, <span class="number">0</span>);</span><br><span class="line">            buffer.clear();</span><br><span class="line">            <span class="keyword">while</span> (!writeOperation.isDone());</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">            System.out.println(<span class="string">&quot;写入完成&quot;</span>);</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">fileChannel =</span><br><span class="line">                   AsynchronousFileChannel.open(Paths.get(<span class="string">&quot;resources\\test3.txt&quot;</span>), StandardOpenOption.WRITE);</span><br><span class="line"></span><br><span class="line">           ByteBuffer buffer = ByteBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">           buffer.put(<span class="string">&quot;asynchronousFileChannel&quot;</span>.getBytes());</span><br><span class="line">           buffer.flip();</span><br><span class="line">           fileChannel.write(buffer, <span class="number">0</span>, buffer, <span class="keyword">new</span> CompletionHandler&lt;Integer, ByteBuffer&gt;() &#123;</span><br><span class="line">               <span class="meta">@Override</span></span><br><span class="line">               <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">completed</span><span class="params">(Integer result, ByteBuffer attachment)</span> </span>&#123;</span><br><span class="line">                   System.out.println(<span class="string">&quot;写入完成&quot;</span> + result);</span><br><span class="line">               &#125;</span><br><span class="line"></span><br><span class="line">               <span class="meta">@Override</span></span><br><span class="line">               <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">failed</span><span class="params">(Throwable exc, ByteBuffer attachment)</span> </span>&#123;</span><br><span class="line">                   System.out.println(<span class="string">&quot;写入失败&quot;</span>);</span><br><span class="line">               &#125;</span><br><span class="line">           &#125;);</span><br></pre></td></tr></table></figure>
<h2 id="字符集Charset"><a href="#字符集Charset" class="headerlink" title="字符集Charset"></a>字符集Charset</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取系统支持的所有编码方式</span></span><br><span class="line">        SortedMap&lt;String, Charset&gt; stringCharsetSortedMap = Charset.availableCharsets();</span><br><span class="line">        Set&lt;Map.Entry&lt;String, Charset&gt;&gt; entries = stringCharsetSortedMap.entrySet();</span><br><span class="line">        <span class="keyword">for</span> (Map.Entry&lt;String, Charset&gt; entry : entries) &#123;</span><br><span class="line">            System.out.println(entry.getKey() + <span class="string">&quot;-&gt;&quot;</span> + entry.getValue());</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取虚拟机默认的编码方式</span></span><br><span class="line">        System.out.println(Charset.defaultCharset().name());</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 判断是否支持该编码</span></span><br><span class="line">        <span class="keyword">if</span> (Charset.isSupported(<span class="string">&quot;UTF-8&quot;</span>)) &#123;</span><br><span class="line">            System.out.println(<span class="string">&quot;支持UTF-8&quot;</span>);</span><br><span class="line">        &#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">Charset charset = Charset.forName(<span class="string">&quot;UTF-8&quot;</span>);</span><br><span class="line">        <span class="comment">// 获取编码器</span></span><br><span class="line">        CharsetEncoder charsetEncoder = charset.newEncoder();</span><br><span class="line">        <span class="comment">// 获取解码器</span></span><br><span class="line">        CharsetDecoder charsetDecoder = charset.newDecoder();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取需要解码编码的数据</span></span><br><span class="line">        CharBuffer buffer = CharBuffer.allocate(<span class="number">1024</span>);</span><br><span class="line">        buffer.put(<span class="string">&quot;字符集&quot;</span>);</span><br><span class="line">        buffer.flip();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 编码</span></span><br><span class="line">        ByteBuffer encode = charsetEncoder.encode(buffer);</span><br><span class="line">        System.out.print(<span class="string">&quot;编码后: &quot;</span>);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; encode.limit(); i++) &#123;</span><br><span class="line">            System.out.print(encode.get() + <span class="string">&quot; &quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 解码</span></span><br><span class="line">        encode.flip();</span><br><span class="line">        CharBuffer decode = charsetDecoder.decode(encode);</span><br><span class="line">        System.out.println();</span><br><span class="line">        System.out.print(<span class="string">&quot;解码后：&quot;</span>);</span><br><span class="line">        System.out.print(decode.toString());</span><br></pre></td></tr></table></figure>


        <hr>
        <!-- Pager -->
        <ul class="pager">
          
          <li class="previous">
            <a href="/cn/nginx/nginx基础篇/" data-toggle="tooltip" data-placement="top" title="nginx基础篇">&larr; Previous Post</a>
          </li>
          
          
          <li class="next">
            <a href="/cn/mysql/MySQL基础（一）/" data-toggle="tooltip" data-placement="top" title="MySQL基础（一）">Next Post &rarr;</a>
          </li>
          
        </ul>

        
        <!-- tip start -->
        <!-- tip -->
<!-- tip start -->
<div class="tip">
  <p>
    
      如果您喜欢此博客或发现它对您有用，则欢迎对此发表评论。 也欢迎您共享此博客，以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权，请与作者联系以将其删除。 谢谢 ！
    
  </p>
</div>
<!-- tip end -->

        <!-- tip end -->
        

        
        <hr>

        <!-- comments start -->
        <!-- 1. gitalk comment -->


<!-- 2. gitment comment -->


<!-- 3. disqus comment -->


        <!-- comments end -->
        <hr>

      </div>

      <!-- Catalog: Tabe of Content -->
      <!-- Table of Contents -->



      <!-- Sidebar Container -->
      <div class="
                col-lg-8 col-lg-offset-1
                col-md-10 col-md-offset-1
                sidebar-container">

        <!-- Featured Tags -->
        
        <section>
          <!-- no hr -->
          <h5>
            <a href="/tags/">特色标签</a>
          </h5>
          <div class="tags">
            
            <a class="tag" href="/tags/#java" title="java">java</a>
            
          </div>
        </section>
        

        <!-- Friends Blog -->
        
        <hr>
        <h5>链友</h5>
        <ul class="list-inline">

          
        </ul>
        
      </div>
    </div>
  </div>
</article>



<!-- anchorjs start -->
<!-- async load function -->
<!-- anchor-js, Doc:http://bryanbraun.github.io/anchorjs/ -->
<script type="text/javascript">
  // async load function
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function(e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  };
</script>
<script type="text/javascript">
  //anchor-js, Doc:http://bryanbraun.github.io/anchorjs/
  async ("https://cdn.bootcss.com/anchor-js/1.1.1/anchor.min.js", function() {
    anchors.options = {
      visible: 'hover',
      placement: 'left',
      // icon: 'ℬ'
      icon: '❡'
    };
    anchors.add().remove('.intro-header h1').remove('.subheading').remove('.sidebar-container h5');
  });
</script>
<style>
  /* place left on bigger screen */
  @media all and (min-width: 800px) {
    .anchorjs-link {
      position: absolute;
      left: -0.75em;
      font-size: 1.1em;
      margin-top: -0.1em;
    }
  }
</style>

<!-- anchorjs end -->



		<!-- Footer (contains ThemeColor、viewer) -->
		<!-- Footer -->
<footer>
  <div class="container">
    <div class="row">
      <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
        <ul class="list-inline text-center">
          

          

          

          

          

          

          

          

        </ul>
        <p class="copyright text-muted">
          Copyright &copy;
          zhuang
          2021
          <br>
          Theme by
          <a target="_blank" rel="noopener" href="http://beantech.org">BeanTech</a>
          <span style="display: inline-block; margin: 0 5px;">
            <i class="fa fa-heart"></i>
          </span>
          re-Ported by
          <a target="_blank" rel="noopener" href="https://v-vincen.life/">Live My Life</a>
        </p>
      </div>
    </div>
  </div>
</footer>

<a id="rocket" href="#top" class=""></a>


  <!-- jQuery -->
  <script type="text/javascript" src="/js/jquery.min.js"></script>
  <!-- Bootstrap Core JavaScript -->
  <script type="text/javascript" src="/js/bootstrap.min.js"></script>
  <!-- Custom Theme JavaScript -->
  <script type="text/javascript" src="/js/hux-blog.min.js"></script>
  <!-- catalog -->
  <script async="true" type="text/javascript" src="/js/catalog.js"></script>
  <!-- totop(rocket) -->
  <script async="true" type="text/javascript" src="/js/totop.js"></script>

  
    <!-- Busuanzi JavaScript -->
    <script async="async" src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
  

  
    <!-- Scroll start -->
    <script async="async" type="text/javascript" src="/js/scroll.js"></script>
    <!-- Scroll end -->
  

  

  

  
    <!-- ribbon -->
    <script type="text/javascript" src="/js/ribbonDynamic.js"></script>
  

  






  <!-- viewer start -->
  <!-- viewer start (Picture preview) -->
  
    <script async="async" type="text/javascript" src="/js/viewer/viewer.min.js"></script>
    <script async="async" type="text/javascript" src="/js/viewer/pic-viewer.js"></script>
  

  <!-- viewer end -->


<script>
  // async load function
  function async (u, c) {
    var d = document,
      t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) {
      o.addEventListener('load', function (e) {
        c(null, e);
      }, false);
    }
    s.parentNode.insertBefore(o, s);
  }

  // fastClick.js
  async ("https://cdn.bootcss.com/fastclick/1.0.6/fastclick.min.js", function () {
    var $nav = document.querySelector("nav");
    if ($nav)
      FastClick.attach($nav);
    }
  )
</script>

<!-- Because of the native support for backtick-style fenced code blocks right within the Markdown is landed in Github Pages, From V1.6, There is no need for Highlight.js, so Huxblog drops it officially. -
https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0 - https://help.github.com/articles/creating-and-highlighting-code-blocks/ -->
<!-- <script> async ("http://cdn.bootcss.com/highlight.js/8.6/highlight.min.js", function () { hljs.initHighlightingOnLoad(); }) </script> <link href="http://cdn.bootcss.com/highlight.js/8.6/styles/github.min.css" rel="stylesheet"> -->

<!-- jquery.tagcloud.js -->
<!-- <script> // only load tagcloud.js in tag.html if ($('#tag_cloud').length !== 0) { async ("http://yoursite-url/js/jquery.tagcloud.js", function () { $.fn.tagcloud.defaults = { // size: { start: 1, end: 1, unit: 'em' }, color: {
start: '#bbbbee', end: '#0085a1' } }; $('#tag_cloud a').tagcloud(); }) } </script> -->


		<!-- Search -->
		
		<div class="popup search-popup local-search-popup">
  <span class="popup-btn-close">
    ESC
  </span>
  <div class="container">
    <div class="row">
      <!-- <div class="col-md-9 col-md-offset-1"> -->
      <div class="col-lg-9 col-lg-offset-1 col-md-10 col-md-offset-1 local-search-content">

        <div class="local-search-header clearfix">

          <div class="local-search-input-wrapper">
            <span class="search-icon">
              <i class="fa fa-search fa-lg" style="margin: 25px 10px 25px 20px;"></i>
            </span>
            <input autocomplete="off" placeholder="搜索..." type="text" id="local-search-input">
          </div>
        </div>
        <div id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>


  
    <script src="/js/ziploader.js"></script>
  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.json";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    // monitor main search box;
    var onPopupClose = function (e) {
      $('.popup').fadeOut(300);
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $('.popup').fadeIn(300);
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }
    // get search zip version
    $.get('/searchVersion.json?t=' + (+new Date()), function (res) {
      if (localStorage.getItem('searchVersion') !== res) {
        localStorage.setItem('searchVersion', res);
        initSearchJson();
      }
    });

    function initSearchJson() {
      initLoad(['/search.flv'], {
        loadOptions: {
          success: function (obj) {
            localStorage.setItem('searchJson', obj['search.json'])
          },
          error: function (e) {
            return console.log(e)
          }
        },
        returnOptions: {
          'json': TYPE_TEXT
        },
        mimeOptions: {
          'json': 'application/json'
        }
      })
    }
    // search function;
    var searchFunc = function (search_id, content_id) {
      'use strict';
      isfetched = true;
      var datas = JSON.parse(localStorage.getItem('searchJson'));
      // console.log(search_id)
      var input = document.getElementById(search_id);
      var resultContent = document.getElementById(content_id);
      var inputEventFunction = function () {
        var searchText = input.value.trim().toLowerCase();
        var keywords = searchText.split(/[\s\-]+/);
        if (keywords.length > 1) {
          keywords.push(searchText);
        }
        var resultItems = [];
        if (searchText.length > 0) {
          // perform local searching
          datas.forEach(function (data) {
            var isMatch = false;
            var hitCount = 0;
            var searchTextCount = 0;
            var title = data.title
              ? data.title.trim()
              : '';
            var titleInLowerCase = title.toLowerCase();
            var content = data.content
              ? data.content.trim().replace(/<[^>]+>/g, "")
              : '';
            var contentInLowerCase = content.toLowerCase();
            var articleUrl = decodeURIComponent(data.url);

            var date = data.date;
            var dateTime = date.replace(/T/, " ").replace(/.000Z/, "");
            var imgUrl = data.header_img;
            


            var indexOfTitle = [];
            var indexOfContent = [];
            // only match articles with not empty titles
            keywords.forEach(function (keyword) {
              function getIndexByWord(word, text, caseSensitive) {
                var wordLen = word.length;
                if (wordLen === 0) {
                  return [];
                }
                var startPosition = 0,
                  position = [],
                  index = [];
                if (!caseSensitive) {
                  text = text.toLowerCase();
                  word = word.toLowerCase();
                }
                while ((position = text.indexOf(word, startPosition)) > -1) {
                  index.push({position: position, word: word});
                  startPosition = position + wordLen;
                }
                return index;
              }
              indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
              indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
            });
            if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
              isMatch = true;
              hitCount = indexOfTitle.length + indexOfContent.length;
            }
            // show search results
            if (isMatch) {
              // sort index by position of keyword
              [indexOfTitle, indexOfContent].forEach(function (index) {
                index.sort(function (itemLeft, itemRight) {
                  if (itemRight.position !== itemLeft.position) {
                    return itemRight.position - itemLeft.position;
                  } else {
                    return itemLeft.word.length - itemRight.word.length;
                  }
                });
              });
              // merge hits into slices
              function mergeIntoSlice(text, start, end, index) {
                var item = index[index.length - 1];
                var position = item.position;
                var word = item.word;
                var hits = [];
                var searchTextCountInSlice = 0;
                while (position + word.length <= end && index.length != 0) {
                  if (word === searchText) {
                    searchTextCountInSlice++;
                  }
                  hits.push({position: position, length: word.length});
                  var wordEnd = position + word.length;
                  // move to next position of hit
                  index.pop();
                  while (index.length != 0) {
                    item = index[index.length - 1];
                    position = item.position;
                    word = item.word;
                    if (wordEnd > position) {
                      index.pop();
                    } else {
                      break;
                    }
                  }
                }
                searchTextCount += searchTextCountInSlice;
                return {hits: hits, start: start, end: end, searchTextCount: searchTextCountInSlice};
              }
              var slicesOfTitle = [];
              if (indexOfTitle.length != 0) {
                slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
              }
              var slicesOfContent = [];
              while (indexOfContent.length != 0) {
                var item = indexOfContent[indexOfContent.length - 1];
                var position = item.position;
                var word = item.word;
                // cut out 100 characters
                var start = position - 20;
                var end = position + 80;
                if (start < 0) {
                  start = 0;
                }
                if (end < position + word.length) {
                  end = position + word.length;
                }
                if (end > content.length) {
                  end = content.length;
                }
                slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
              }
              // sort slices in content by search text's count and hits' count
              slicesOfContent.sort(function (sliceLeft, sliceRight) {
                if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                  return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                  return sliceRight.hits.length - sliceLeft.hits.length;
                } else {
                  return sliceLeft.start - sliceRight.start;
                }
              });
              // select top N slices in content
              var upperBound = parseInt('1');
              if (upperBound >= 0) {
                slicesOfContent = slicesOfContent.slice(0, upperBound);
              }
              // highlight title and content
              function highlightKeyword(text, slice) {
                var result = '';
                var prevEnd = slice.start;
                slice.hits.forEach(function (hit) {
                  result += text.substring(prevEnd, hit.position);
                  var end = hit.position + hit.length;
                  result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                  prevEnd = end;
                });
                result += text.substring(prevEnd, slice.end);
                return result;
              }
              var resultItem = '';

              // if (slicesOfTitle.length != 0) {   resultItem += "<li><a target='_blank' href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>"; } else {   resultItem += "<li><a target='_blank' href='" +
              // articleUrl + "' class='search-result-title'>" + title + "</a>"; } slicesOfContent.forEach(function (slice) {   resultItem += "<a target='_blank' href='" + articleUrl + "'><p class=\"search-result\">" + highlightKeyword(content, slice) +
              // "...</p></a>"; }); resultItem += "</li>";

              if (slicesOfTitle.length != 0) {
                resultItem += "<a target='_blank' href='" + articleUrl + "' class='search-result'><div class='search-result-left'><div class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</div><time class='search-result-date'>" + dateTime + "</time>";
              } else {
                resultItem += "<a target='_blank' href='" + articleUrl + "' class='search-result'><div class='search-result-left'><div class='search-result-title'>" + title + "</div><time class='search-result-date'>" + dateTime + "</time>";
              }
              slicesOfContent.forEach(function (slice) {
                resultItem += "<p class=\"search-result-content\">" + highlightKeyword(content, slice) + "...</p>";
              });
              resultItem += "</div><div class='search-result-right'><img class='media-image' src='" + imgUrl + "' width='64px' height='48px'></img></div></a>";

              resultItems.push({item: resultItem, searchTextCount: searchTextCount, hitCount: hitCount, id: resultItems.length});
            }
          })
        };

        if (keywords.length === 1 && keywords[0] === "") {
          resultContent.innerHTML = '<div id="no-result"></div>'
        } else if (resultItems.length === 0) {
          resultContent.innerHTML = '<div id="no-result"></div>'
        } else {
          resultItems.sort(function (resultLeft, resultRight) {
            if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
              return resultRight.searchTextCount - resultLeft.searchTextCount;
            } else if (resultLeft.hitCount !== resultRight.hitCount) {
              return resultRight.hitCount - resultLeft.hitCount;
            } else {
              return resultRight.id - resultLeft.id;
            }
          });
          var searchResultList = '<div class=\"search-result-list\">';
          resultItems.forEach(function (result) {
            searchResultList += result.item;
          })
          searchResultList += "</div>";
          resultContent.innerHTML = searchResultList;
        }
      }
      if ('auto' === 'auto') {
        input.addEventListener('input', inputEventFunction);
      } else {
        $('.search-icon').click(inputEventFunction);
        input.addEventListener('keypress', function (event) {
          if (event.keyCode === 13) {
            inputEventFunction();
          }
        });
      }
      // remove loading animation
      $('body').css('overflow', '');
      proceedsearch();
    }
    // handle and trigger popup window;
    $('.popup-trigger').click(function (e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc('local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });
    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function (e) {
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 && $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });

    document.addEventListener('mouseup', (e) => {
      var _con = document.querySelector(".local-search-content");
      if (_con) {
        if (!_con.contains(e.target)) {
          onPopupClose();
        }
      }
    });
  </script>


		
	<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html>
